<template>
  <div class="pms-zr-upload-attach">
    <div v-for="(item,index) in uploadArray" :key="index" class="uploadBox">
      <div class="header">
        <div class="header-left">
          <div class="search-list-icon" />
          <div class="search-list-title"><span
            v-if="+item.isMust === 1"
            style="color: #eb4b4b "
          >*</span>{{ item.docTypeName }}<span
            v-if="+item.isMust === 1"
          >（必传）</span></div>
        </div>
        <div class="header-right">
          <el-button
            class="pms-button-primary-plain"
            style="min-width: 75px !important;"
            @click="clearAll(index)"
          >全部清除
          </el-button>
          <el-upload
            class="upload-file"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleChangeAdd.bind(null, index)"
          >
            <el-button class="pms-button-primary-plain">添加</el-button>
          </el-upload>
        </div>
      </div>
      <el-upload
        v-if="item.listFile.length===0"
        drag
        class="upload-file"
        action="#"
        :on-change="handleChange.bind(null, index)"
        :limit="10"
        :auto-upload="false"
        :on-exceed="handleExceed"
        :file-list="item.listFileInit"
        :show-file-list="false"
        multiple
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">火狐浏览器可尝试托拽文件进行上传或使用微信截图粘贴<br>单次选择文件不超过10个、总体文件大小不超过300M
        </div>
      </el-upload>
      <div v-for="(v,i) in item.listFile" :key="i" class="data-item">
        <div class="data-item-left">
          <i
            v-if="v.status!=='success'"
            class="el-icon-error"
            style="color: #d81e06;font-size: 18px;cursor: pointer"
            @click="beforeRemove(index,i,v)"
          />
          <div class="data-item-name">{{ v.name }}</div>
        </div>
        <div class="data-item-right">
          <div v-if="showSelect">
              <div
                  v-if="(item.docFileType==='D44'||item.docFileType==='D45') && selectArray.length>0"
                  style="display: flex;align-items: center;width: 130px"
                  class="singleProject"
              >
                  <span style="color: #eb4b4b;margin-right: 3px ">*</span>
                  <el-select
                      v-model="v.prjId"
                      placeholder="选择单项工程"
                      size="mini"
                      style="width: 125px"
                      :popper-append-to-body="false"
                      :disabled="v.status==='success'"
                  >
                      <el-option
                          v-for="items in selectArray"
                          :key="items.prjId"
                          :label="items.prjCode"
                          :value="items.prjId"
                      />
                  </el-select>
              </div>
              <div class="signature" style="display: flex;align-items: center;width: 120px;margin-left: 5px;">
                  <span style="color: #eb4b4b;margin-right: 3px ">*</span>
                  <el-select
                      v-model="v.isSignature"
                      placeholder="电子签章"
                      size="mini"
                      style="width: 100%"
                      :popper-append-to-body="false"
                      :disabled="v.status==='success'||!v.isSelectSignature"
                  >
                      <el-option
                          v-for="items in signatureArray"
                          :key="items.code"
                          :label="items.name"
                          :value="items.code"
                      />
                  </el-select>
              </div>
          </div>
          <div>
            <div v-if="v.status==='ready'" class="data-item-right-label" style=" white-space: nowrap;margin-left: 10px;">待上传</div>
            <i v-else-if="v.status==='loading'" class="el-icon-loading" style="font-size: 18px;margin-left: 28px;" />
            <i
              v-else-if="v.status==='fail'"
              class="el-icon-warning"
              style="color: #d81e06;font-size: 18px;margin-left: 28px;"
            />
            <i
              v-else-if="v.status==='success'"
              class="el-icon-success"
              style="color: #07C160;font-size: 18px;margin-left: 28px;"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
    import { msgInfoEl } from '@/utils'
    import { txBatchUpload, uploadSignInfoApi, queryFileWhitelist } from '@/api/attachmentInfo'

    export default {
        name: 'UploadAttach',
        components: {},
        props: {
            // 页面路由中参数
            prjParams: {
                type: Object,
                default: () => ({})
            },
            // 父组件所传文件类型字典选项
            prjFileTypeOption: {
                type: Array,
                default: () => []
            },
            // 单项工程列表集合
            selectArray: {
              type: Array,
              default: () => []
            },
            //部分不需要选择单项工程列表和是否电子签章
            showSelect:{
                type:Boolean,
                default:true
            }
        },
        data() {
            return {
                uploadArray: [],
                signatureArray: [
                    {
                        code: '1',
                        name: '电子签章,是'
                    },
                    {
                        code: '0',
                        name: '电子签章,否'
                    }
                ],
                typeArray: '',
                signatureTypeArray: '',
            }
        },
        watch: {},
        created() {
            for (let i = 0; i < this.prjFileTypeOption.length; i++) {
                this.uploadArray.push({
                    docFileType: this.prjFileTypeOption[i].typeCode,
                    docTypeName: this.prjFileTypeOption[i].typeName,
                    fileFormatType: this.prjFileTypeOption[i].fileFormatType,
                    isMust: this.prjFileTypeOption[i].isMust,
                    listFile: [],
                    listFileInit: []
                })
            }
            this.queryFileWhitelist('01')
            this.queryFileWhitelist('02')
        },
        methods: {
            // 获取到单项工程下拉列表数据
            queryFileWhitelist(type) {
                queryFileWhitelist(type).then((res) => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    }
                    if(type === '01'){
                        this.typeArray = res.data
                    }else{
                        this.signatureTypeArray = res.data
                    }
                })
            },
            // 改变状态
            changeStatus(list) {
                const readyList = []
                for (let i = 0; i < list.length; i++) {
                    for (let j = 0; j < list[i].listFile.length; j++) {
                        if (this.uploadArray[i].listFile[j].status === 'ready' || this.uploadArray[i].listFile[j].status === 'fail') {
                            this.uploadArray[i].listFile[j].status = 'loading'
                            readyList.push(this.uploadArray[i].listFile[j])
                        }
                    }
                }
                if (readyList.length === 0) {
                    msgInfoEl({
                        type: 'error',
                        message: `当前附件已完成上传，请添加新附件或关闭页面!`
                    })
                }
            },
            // 判断内部验收证书和项目验收报告是否选择归属单项工程
            getSingleProject(arr) {
                const status = []
                arr.forEach((item) => {
                    if ((item.docFileType === 'D44' || item.docFileType === 'D45') && this.selectArray.length > 0 && item.listFile.length > 0) {
                        item.listFile.forEach((child) => {
                            if (child.prjId) {
                                status.push(true)
                            } else {
                                status.push(false)
                            }
                        })
                    }
                })
                return status.includes(false)
            },
            // 判断电子签章是否填写
            getSignature(arr) {
                const status = []
                arr.forEach((item) => {
                    item.listFile.forEach((child) => {
                        if (child.isSelectSignature) {
                            if (child.isSignature) {
                                status.push(true)
                            } else {
                                status.push(false)
                            }
                        }
                    })
                })
                return status.includes(false)
            },
            startUpload() {
                console.log('this.uploadArray', this.uploadArray)
                const flagA = this.getSingleProject(this.uploadArray)
                const flagB = this.getSignature(this.uploadArray)
                if (flagA) {
                    msgInfoEl({
                        type: 'error',
                        message: `当前存在未选择归属单项工程的附件，请在下拉框中选择!`
                    })
                    return false
                } else if (flagB) {
                    msgInfoEl({
                        type: 'error',
                        message: `当前存在未选择是否电子签章的附件，请在下拉框中选择!`
                    })
                    return false
                } else {
                    this.changeStatus(this.uploadArray)
                    this.optimizeNewOne()
                }
            },
            // 2024-9-26 阻断问题if过多解决方案
            optimizeNewOne() {
                this.uploadArray.forEach((item) => {
                        if (item.listFile.length > 0) {
                            this.optimizeNewTwo(item)
                        }
                    })
            },
             // 2024-9-26 阻断问题if过多解决方案
             optimizeNewTwo(item) {
                item.listFile.forEach((child) => {
                                if (child.status === 'loading') {
                                    const params = {
                                        docFileType: item.docFileType, // Z15----RYC
                                        file: child.raw,
                                        // SIGN + taskId
                                        prjId: this.getChildPrjID(item, child),
                                        activityId: this.prjParams.nodeId,
                                        prjStage: this.prjParams.prjStage, // E
                                        isChange: '0', // 0:正常上传的,1:整改的,2:继承的
                                        operateSystem: '0', // 操作系统，0:PMS,1:施工管理
                                        operateType: '1' // 操作类型，1:新增，2:补传
                                        // isSignFile: '01'
                                    }
                                    const params1 = {
                                        ...params,
                                        processId: this.prjParams.processId
                                    }
                                    if (child.isSignature === '1') {
                                        const formData = new FormData()
                                        Object.keys(params).forEach(key =>
                                            formData.append(key, params[key])
                                        )
                                        uploadSignInfoApi(formData).then(res => {
                                            // if (+res.code === 200) {
                                            //     child.status = 'success'
                                            // } else {
                                            //     child.status = 'fail'
                                            // }
                                            child.status = +res.code === 200 ? 'success' : 'fail'
                                        }).catch(() => {
                                            child.status = 'fail'
                                        })
                                    } else {
                                        const formData1 = new FormData()
                                        Object.keys(params1).forEach(key =>
                                            formData1.append(key, params1[key])
                                        )
                                        txBatchUpload(formData1).then(_res => {
                                            // if (+res.code === 200) {
                                            //     child.status = 'success'
                                            // } else {
                                            //     child.status = 'fail'
                                            // }
                                            child.status = +_res.code === 200 ? 'success' : 'fail'
                                        }).catch(() => {
                                            child.status = 'fail'
                                        })
                                    }
                                }
                            })
             },
             getChildPrjID(item, child) {
                return (item.docFileType === 'D44' || item.docFileType === 'D45') && this.selectArray.length > 0 ? child.prjId : this.prjParams.prjId
             },
            // 文件列表移除文件时的钩子
            beforeRemove(index, i, file) {
                const msg = this.$confirm(`确定移除 ${file.name}?`, {
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary'
                }).then(() => {
                    this.uploadArray[index].listFile.splice(i, 1)
                })
                // 将弹框挂载在最外层
                const contentBody = window.top.document.body
                this.$nextTick(() => {
                    const msgBox = document.querySelector('.el-message-box__wrapper')
                    contentBody.appendChild(msgBox)
                })
                return msg
            },
            // 文件超出个数限制时的钩子
            handleExceed() {
                msgInfoEl({
                    type: 'error',
                    message: '当前限制选择 10 个文件'
                })
            },
            // 上传前,判断文件整体大小是否超过300M
            beforeUpload(fileList) {
                let fileSize = 0
                for (let i = 0; i < fileList.length; i++) {
                    fileSize += fileList[i].size
                }
                if (fileSize / 1024 / 1024 > 300) {
                    msgInfoEl({
                        type: 'error',
                        message: `总体文件大小不超过300M!`
                    })
                    return false
                }
                return true
            },
            // 判断文件类型是否符合要求
            beforeUploadType(index, file) {
                const fileContent = file.raw
                const fileTypeMap = this.uploadArray[index]
                const types = file.name.substring(file.name.lastIndexOf('.') + 1) // 获取文件类型
                const typesStr = `*.${types}`

                const isFileType = fileTypeMap.fileFormatType === typesStr

                if (fileTypeMap.fileFormatType !== '*.*' && !isFileType && !fileContent) {
                    msgInfoEl({
                        type: 'warning',
                        message: `格式错误！请重新选择,仅支持${typesStr}格式的文件`
                    })
                    return false
                }
                if (fileTypeMap.fileFormatType === '*.*' && !this.typeArray.includes(types)) {
                    msgInfoEl({
                        type: 'warning',
                        message: `目前仅支持以下格式附件进行上传:${this.typeArray}`
                    })
                    return false
                }
                return true
            },
            // 初始上传时
            handleChange(index, file, fileList) {
                const flag = this.beforeUpload(fileList) && this.beforeUploadType(index, file)
                if (flag) {
                    this.uploadArray[index].listFile = []
                    fileList.forEach((item) => {
                        const types = item.name.substring(item.name.lastIndexOf('.') + 1) // 获取文件类型
                        this.uploadArray[index].listFile.push({
                            ...item,
                            prjId: '',
                            isSignature: '0',
                            isSelectSignature: this.signatureTypeArray.includes(types)
                        })
                    })
                } else {
                    this.uploadArray[index].listFile = []
                }
                if (this.uploadArray[index].listFile.length !== fileList.length) {
                    this.uploadArray[index].listFileInit = []
                }
            },
            // 添加上传时，判断是否有同名文件
            getSomeName(name, arr) {
                return arr.some(item => item.name === name)
            },
            // 添加按钮
            handleChangeAdd(index, file) {
                const isSome = this.getSomeName(file.name, this.uploadArray[index].listFile)
                const types = file.name.substring(file.name.lastIndexOf('.') + 1) // 获取文件类型
                if (isSome) {
                    const msg = this.$confirm(`${file.name}文件已存在，点击确定将替换该文件?`, {
                        cancelButtonClass: 'pms-zr-button',
                        confirmButtonClass: 'pms-zr-button-primary'
                    }).then(() => {
                        // 先替换，再判断总大小是否超出
                        const newFileList = this.uploadArray[index].listFile.map(item => {
                            return file.name === item.name ? { ...file, prjId: '', isSignature: '0', isSelectSignature: this.signatureTypeArray.includes(types) } : item
                        })
                        const flag = this.beforeUpload(newFileList) && this.beforeUploadType(index, file)
                        if (flag) {
                            this.uploadArray[index].listFile = newFileList
                        } else {
                            return false
                        }
                    }).catch(() => {
                        return false
                    })
                    // 将弹框挂载在最外层
                    const contentBody = window.top.document.body
                    this.$nextTick(() => {
                        const msgBox = document.querySelector('.el-message-box__wrapper')
                        contentBody.appendChild(msgBox)
                    })
                    return msg
                } else {
                    const arr = this.uploadArray[index].listFile.concat(file)
                    const flag = this.beforeUpload(arr) && this.beforeUploadType(index, file)
                    if (flag) {
                        this.uploadArray[index].listFile.push({
                            ...file,
                            prjId: '',
                            isSignature: '0',
                            isSelectSignature: this.signatureTypeArray.includes(types)
                        })
                    } else {
                        return false
                    }
                }
            },
            // 全部清除
            clearAll(index) {
                if (this.uploadArray[index].listFile.length === 0) {
                    msgInfoEl({
                        type: 'warning',
                        message: `当前没有可清除的附件，请上传附件!`
                    })
                    return false
                } else {
                    const flag = this.uploadArray[index].listFile.some((item) => item.status === 'success')
                    if (flag) {
                        msgInfoEl({
                            type: 'warning',
                            message: `请在附件信息列表对已上传成功的附件进行删除！`
                        })
                    } else {
                        const msg = this.$confirm(`确定移除全部文件吗?`, {
                            cancelButtonClass: 'pms-zr-button',
                            confirmButtonClass: 'pms-zr-button-primary'
                        }).then(() => {
                            this.uploadArray[index].listFile = []
                        })
                        // 将弹框挂载在最外层
                        const contentBody = window.top.document.body
                        this.$nextTick(() => {
                            const msgBox = document.querySelector('.el-message-box__wrapper')
                            contentBody.appendChild(msgBox)
                        })
                        return msg
                    }
                }
            }
        }
    }
</script>

<style lang="scss" scoped>

    ::v-deep .el-upload-list__item {
        line-height: none;
        margin-top: 5px;

        .el-upload-list__item .is-ready {
            margin-top: 0;
        }
    }

    ::v-deep .el-upload-list__item-name {
        margin-right: 0;
        font-size: 12px;
        width: 300px;
    }

    ::v-deep .el-button--mini, .el-button--small {
        color: #fff;
        background-color: #eb4b4b;
    }

    ::v-deep .el-radio__input.is-checked + .el-radio__label {
        color: #eb4b4b;
    }

    ::v-deep .el-radio__input.is-checked .el-radio__inner {
        border-color: #eb4b4b;
        background: #eb4b4b;
    }

    //::v-deep .el-upload {
    //    width: 100%;
    //}

    //::v-deep .el-upload-dragger {
    //    width: 100%;
    //    height: 80px;
    //    display: flex;
    //    justify-content: center;
    //    align-items: center;
    //}

    //::v-deep .el-upload-dragger .el-icon-upload {
    //    margin: 0;
    //}

    ::v-deep .el-input--mini .el-input__inner {
        //width: 95px !important;
        height: 24px;
    }

    ::v-deep .el-select-dropdown__wrap{
        max-height: 180px !important;
    }
</style>
